<?php

namespace App\Repository\Repositories;

use App\Repository\Models\Orders;
use App\Repository\Repositories\Interfaces\OrdersRepository;

/**
 * Class OrderRepositoryEloquent.
 * @todo 自定义BaseRepository继承自原BaseRepository
 * @package namespace App\Repository\Repositories;
 */
class OrdersRepositoryEloquent extends BaseRepository implements OrdersRepository
{
    /**
     * 搜索
     * @var array
     */
    protected $fieldSearchable = [
        'order_code',
        'user_id',
        'shop_id',
        'user.name' => 'like',
        'shop.sp_name' => 'like',
        'order_status'=>'in',
        'order_type',
        'pay_status',
        'order_qualification.status'=>'in', // 服务订单联合查询，暂时使用 2018年6月25日
        'trade_no',
        'created_at' => 'between',
        'pay_at' => 'between',
        'order_at' => 'between',
        'receivable_at' => 'between',
        'receivable_type',
        'order_type',
    ];

    /**
     * 将前端字段名替换为关联查询模式
     * @var array
     */
    public $fieldSearchReplace = [
        'status' => 'order_qualification.status',// 服务订单联合查询，暂时使用 2018年6月25日
        'user_name' => 'user.name',
        'shop_name' => 'shop.sp_name',
    ];

    /**
     * 多字段联合模糊查询,前端查询字段名keyword
     * @var array
     */
    public $fieldFuzzySearch = [
        'remark',
        'order_code',
        'orderProducts.product_name',
        'items_products.product_name',
    ];

    /**
     * 可关联查询的字段
     */
    public $withAllow = [
        'order_qualification',
        'orderProducts',
        'user' => ['id', 'name', 'phone', 'address', 'email', 'personal_enterprise'],
        'invoice',
        'orderExpress' => ['order_code', 'express_company', 'id', 'company_code', 'waybill_number'],
        'shop' => ['sp_id', 'sp_name','sp_cmp_id'],
//        'shop' => ['id', 'company_name', 'company_tel'],
        'orderProductComment',
        'userContracts'=>['id','order_id','contracts_name','contracts_code','content','user_id'],
        'items_information' =>['id','item_code','quote_contain','quote_trade_time','seller_phone'],
        'items_products' ,

    ];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Orders::class;
    }

    public function checkAuth($order_code, $shop_id)
    {
        $ret = $this->findWhere(['order_code' => $order_code, 'shop_id' => $shop_id]);
        return $ret ? true : false;
    }

    /**
     * @param $order_id
     * @return bool|float|int
     */
    public function recount($order_id)
    {
        $order = $this->query()->with(['orderProducts'])->find($order_id);
        $ret = false;
        if ($order_products = array_get($order, 'orderProducts')) {
            $product_money = 0.00;
            $freight = 0.00;
            $discount_money = 0.00;
            foreach ($order_products as $order_product) {
                $product_money += $order_product['product_money'];
                $freight += $order_product['freight'];
                $discount_money += $order_product['discount_money'];
            }
            $order_money = $product_money + $freight;
            $ret = $order->update(['product_money' => $product_money, 'freight' => $freight, 'discount_money' => $discount_money, 'order_money' => $order_money]);
        }
        return $ret ? $order_money : $ret;
    }

    public function findByOrderCode($order_code)
    {
        $this->applyCriteria();
        $this->applyScope();

        $model = $this->model->where('order_code', $order_code)->first();

        if(!$model){
            return null;
        }

        $this->resetModel();
        return $this->parserResult($model);
    }

    public function paySuccess($order_codes, $pay_at, $trade_no, $method)
    {
        $data = [
            'order_status' => Orders::ORDER_STATUS_FINISH,
            'pay_status'=>1,
            'pay_at' => $pay_at,
            'trade_no' => $trade_no,
            'pay_method' => $method
        ];
        $ret = $this->query()
            ->whereIn('order_code', $order_codes)
            ->update($data);

        return $ret;
    }

    /**
     * 商城首页最新成交订单
     */
    public function newOrder(){
        $data=$this->query()->with(['orderProducts'=>function($sql){
            $sql->select('order_code','product_name');
        }])->where('order_status',Orders::ORDER_STATUS_AFFIRM)->orderBy('confirm_at','desc')->paginate(30,['id','order_code','confirm_at'])->toArray();
        if(!empty($data['data'])){
            foreach($data['data'] as $k=>$v){
                $data['data'][$k]['order_code']=substr_replace($v['order_code'],'*****',5);
                $data['data'][$k]['confirm_at']=date('H:i',strtotime($v['confirm_at']));
                if(isset($v['order_products'][0])){
                    $order_product=$v['order_products'][0]['product_name'];
                    $data['data'][$k]['order_products']= mb_substr($order_product,0,4,'utf-8');
                }else{
                    $data['data'][$k]['order_products']='';
                }
            }
        }

        return $data['data'];
    }
}
